/*
 * @Author: liuxiao
 * @Date: 2024-02-24 18:33:36
 * @Last Modified by: liuxiao
 * @Last Modified time: 2024-03-03 23:35:41
 * ps:全局异常处理
 */

import { Context, Next } from 'koa'
import { HttpException } from './HttpException'

const catchError = async (ctx: Context, next: Next) => {
  try {
    await next() //下一个中间件函数
  } catch (error: any) {
    if (error instanceof HttpException) {
      ctx.body = {
        result: error.result,
        msg: error.msg,
        errorCode: error.errorCode,
        requestUrl: `${ctx.method} ${ctx.path}`,
        code: error.code
      }
      ctx.response.status = error.statusCode
    } else {
      ctx.body = {
        code: 1,
        msg: '服务器内部错误!',
        error_code: 999,
        requestUrl: `${ctx.method} ${ctx.path}`
      }
      ctx.status = 500
    }
  }
}

export default catchError
